using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;

namespace SB2.Core;

/// <summary>
/// c# 代码片段
/// </summary>
public class ScriptWithCSharp : IDynamicFunction, ITransient
{
    public async Task<object> RunAsync(DynamicFunctionExcDto param)
    {
        if (param.Script == null) throw new Exception("无效脚本");
        var code = param.Script.GetCode();
        // Console.WriteLine(param.Param.ToJson());
        try
        {
            var script = await CSharpScript
            .RunAsync(code, ScriptOptions.Default
            .WithReferences("System.Console", "System", "System.Data.Common", "SB2.Core")
            .AddImports("System", "System.Data")
            , param.Param, typeof(DynamicFunctionTempData));
            return script?.ReturnValue;
        }
        catch (Exception e)
        {
            throw new Exception($"脚本内执行失败：{e.Message}");
        }

    }
}